<?php
class Response {
    
    public static function success($data = null, $message = '操作成功') {
        self::json([
            'code' => SUCCESS_CODE,
            'message' => $message,
            'data' => $data
        ]);
    }
    
    public static function error($message = '操作失败', $code = ERROR_CODE, $data = null) {
        self::json([
            'code' => $code,
            'message' => $message,
            'data' => $data
        ]);
    }
    
    public static function authError($message = '认证失败') {
        self::json([
            'code' => AUTH_ERROR_CODE,
            'message' => $message,
            'data' => null
        ]);
    }
    
    public static function notFound($message = '资源未找到') {
        self::json([
            'code' => NOT_FOUND_CODE,
            'message' => $message,
            'data' => null
        ]);
    }
    
    public static function serverError($message = '服务器错误') {
        self::json([
            'code' => SERVER_ERROR_CODE,
            'message' => $message,
            'data' => null
        ]);
    }
    
    private static function json($data) {
        header('Content-Type: application/json; charset=utf-8');
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: Content-Type, Authorization');
        
        if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
            exit;
        }
        
        echo json_encode($data, JSON_UNESCAPED_UNICODE);
        exit;
    }
}
?>